package cn.zhibang.sannuo.web.config;

import cn.zhibang.sannuo.account.service.impl.AAccountnumderServiceImpl;
import cn.zhibang.sannuo.commons.model.Accountnumber;
import cn.zhibang.sannuo.commons.model.Menu;
import cn.zhibang.sannuo.commons.utils.SaltUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author AdminController
 * @version 1.0.0
 * @ClassName AdminRealm.java
 * @Description TODO
 * @createTime 2021年03月30日 09:49:00
 */
public class AdminRealm extends AuthorizingRealm {

    @Autowired private AAccountnumderServiceImpl accountnumderService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        Subject subject = SecurityUtils.getSubject();
        Accountnumber principal = (Accountnumber)subject.getPrincipal();
        String rnumber = accountnumderService.selAccountnumberRnumber(principal.getAccount());

        info.addRole(rnumber);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        Accountnumber accountnumber = accountnumderService.selAccountnumber(token.getUsername());

        if (accountnumber == null){
            return null;
        }
        if (accountnumber.getState() == false){
            return null;
        }

        String salt = SaltUtil.salt(accountnumber.getApssword(), accountnumber.getSalt());

        ByteSource bytes = ByteSource.Util.bytes(accountnumber.getSalt());

        return new SimpleAuthenticationInfo(accountnumber, accountnumber.getApssword(), bytes, getName());
    }
}
